# 编译器设置
CC = gcc
CFLAGS = -Wall -Wextra -I./UnitySrc
COVERAGE_FLAGS = -fprofile-arcs -ftest-coverage
LDFLAGS = -lgcov --coverage

# 源文件设置
SRCS = $(wildcard *.c)
UNITY_SRC = ./UnitySrc/unity.c

# 构建目录
BUILD_DIR = build
OBJS = $(patsubst %.c,$(BUILD_DIR)/%.o,$(SRCS))
UNITY_OBJ = $(BUILD_DIR)/unity.o

# 目标可执行文件
TARGET = $(BUILD_DIR)/testrunner

# 覆盖率报告目录
COVERAGE_DIR = coverage_report

.PHONY: all test coverage clean

# 默认目标：执行测试并生成覆盖率报告
all: test coverage

# 创建构建目录（如果不存在）
$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# 编译 Unity 测试框架
$(UNITY_OBJ): $(UNITY_SRC) | $(BUILD_DIR)
	$(CC) $(CFLAGS) $(COVERAGE_FLAGS) -c $< -o $@

# 编译所有 C 文件
$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR)
	$(CC) $(CFLAGS) $(COVERAGE_FLAGS) -c $< -o $@

# 链接生成可执行文件
$(TARGET): $(OBJS) $(UNITY_OBJ) | $(BUILD_DIR)
	$(CC) $(LDFLAGS) $^ -o $@

# 运行测试
test: $(TARGET)
	./$(TARGET)

# 生成覆盖率报告
coverage: test
	mkdir -p $(COVERAGE_DIR)
	cd $(BUILD_DIR) && gcov -b -o . ../*.c
	lcov --rc lcov_branch_coverage=1 --rc lcov_condition_coverage=1 --capture --directory $(BUILD_DIR) --output-file $(COVERAGE_DIR)/coverage.info
	genhtml --branch-coverage $(COVERAGE_DIR)/coverage.info --output-directory $(COVERAGE_DIR)

# 清理中间文件（包括 build 目录，保留 HTML 覆盖率报告）
clean:
	rm -rf $(BUILD_DIR) $(COVERAGE_DIR)